<template>
	<div class="video-list table-theme">
        <head-title title="公众号--用户手册"></head-title>
		<el-card>
			<div class="top-menu">
				<div class="menu-left">
                    <select-view
						:option-list="ascList"
						:value="asc"
						placeholder="排序"
						type="asc"
						@value="setSelectValue"
					>
					</select-view>
				</div>

				<div class="menu-right">
					<refresh-button @refresh="refreshPage"></refresh-button>
					<div class="add"><el-button type="primary" @click="onOpenDialog('add')">新增第一级</el-button></div>
				</div>
			</div>
			<p class="data-number">总数据数：{{total}}</p>
			<el-table :data="list" border :tree-props="{children:'children'}" row-key="manual_id">
				<el-table-column label="序号" align="center" prop="manual_id" width="80"></el-table-column>
				<el-table-column label="上级ID" align="center" prop="parent_id" width="80"></el-table-column>
				<el-table-column label="名称" align="center" prop="name" width="180"></el-table-column>
				<el-table-column label="icon" align="center" width="80">
					<template slot-scope="scope">
						<ImgPopover :src="scope.row.logo"></ImgPopover>
					</template>
				</el-table-column>
                <el-table-column label="选中icon" align="center" width="80">
					<template slot-scope="scope">
						<ImgPopover :src="scope.row.logo_click"></ImgPopover>
					</template>
				</el-table-column>
                <el-table-column label="等级" align="center" prop="level" width="80"></el-table-column>
                <el-table-column label="类型" align="center" width="80">
                    <template slot-scope="scope">
                        {{scope.row.type == 1 ? 'C端':(scope.row.type == 2?'B端':'')}}
                    </template>
                </el-table-column>
                <el-table-column label="内容" align="center">
                    <template slot-scope="scope">
                        <div v-html="scope.row.content"></div>
                    </template>
                </el-table-column>
				<el-table-column label="添加时间" align="center" prop="add_time" width="180"></el-table-column>
                <el-table-column label="操作" align="center" width="220">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" v-if="scope.row.level<3" @click="onOpenDialog('next',scope.row)">新增下级</el-button>
                        <el-button size="mini" type="primary" @click="onOpenDialog('edit',scope.row)">编辑</el-button>
                        <el-button size="mini" type="primary" @click="onDel(scope.row.manual_id)">删除</el-button>
                    </template>
                </el-table-column>
			</el-table>
			
		</el-card>
        <el-dialog title="用户手册信息" top="2vh" :visible.sync="is_Dialog" center :modal-append-to-body="false" width="680px" @close="onClose">
			<el-form :model="infoForm" :rules="infoFormRules" ref="infoForm" label-width="120px">
                <el-form-item label="名称:" prop="name">
                    <el-input v-model="infoForm.name"></el-input>
                </el-form-item>
                <el-form-item label="icon:">
                    <el-upload class="avatar-uploader" ref="upload" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload('no_click',res); } " multipleaccept="image/*" > 
					<img v-if="infoForm.logo" :src="infoForm.logo" class="avatar" />
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
                    <el-button type="danger" size="small" @click="reset('no_click')" v-if="infoForm.logo">重置</el-button>
                    <div class="el-upload__tip">小于1MB</div>
                </el-form-item>
                <el-form-item label="选中icon:">
                    <el-upload class="avatar-uploader" ref="upload" action="fakeaction" :show-file-list="false" :http-request=" function(res) { return upload('click',res); } " multipleaccept="image/*" > 
					<img v-if="infoForm.logo_click" :src="infoForm.logo_click" class="avatar" />
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
                    <el-button type="danger" size="small" @click="reset('click')" v-if="infoForm.logo_click">重置</el-button>
                    <div class="el-upload__tip">小于1MB</div>
                </el-form-item>
                <el-form-item label="内容:" style="height:300px">
                    <quill-editor class="ql-editor" ref="myQuillEditor" v-model="infoForm.content" :options="editorOption"></quill-editor>
                </el-form-item>
                <el-form-item label="等级:" prop="level">
                    <el-select v-model="infoForm.level" :disabled="is_disabled" placeholder="请选择">
                        <el-option
                        v-for="item in levelList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="端口" prop="type">
                    <el-select v-model="infoForm.type" placeholder="请选择">
                        <el-option
                        v-for="item in typeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
				<el-button @click="onClose">取 消</el-button>
				<el-button type="primary" @click="confirmClick('infoForm')">确 定</el-button>
			</span>
        </el-dialog>
	</div>
</template>

<script>
import md5 from 'md5';
import ImgPopover from '@/components/ImgPopover';
import SelectView from "@/components/SelectView";
import 'quill/dist/quill.core.css'; // import styles
	import 'quill/dist/quill.snow.css'; // for snow theme
	import 'quill/dist/quill.bubble.css'; // for bubble theme
	import {
		quillEditor,
		Quill
	} from 'vue-quill-editor';
	import {
		container,
		addQuillTitle
	} from 'quill-video-image-module';
	import {
		ImageExtend,
		QuillWatch
	} from 'quill-video-image-module';
	import {
		VideoExtend,
		QuillVideoWatch
	} from 'quill-video-image-module';

	// 引入video模块并注册
	import video from 'quill-video-image-module/video';
	Quill.register(video, true);

	Quill.register('modules/ImageExtend', ImageExtend);
	Quill.register('modules/VideoExtend', VideoExtend);
export default {
	components: {
		ImgPopover,
        quillEditor,
        SelectView
	},
	data() {
		return {
			list: [],
			total: 0,
			page: 1,
            order_by:"add_time",
            asc:1,
            ascList:[
                {
                    value:1,
                    label:"升序"
                },
                {
                    value:2,
                    label:"降序"
                }
            ],
            is_Dialog:false,
            infoForm:{
                name:"",
                parent_id:"",
                level:"",
                type:"",
                content:"",
                logo:"",
                logo_click:""
            },
            // 富文本框参数设置
            editorOption: {
                modules: {
                    ImageExtend: {
                        loading: true, // 可选参数 是否显示上传进度和提示语
                        name: 'file[]', // 图片参数名
                        size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
                        action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
                        // response 为一个函数用来获取服务器返回的具体图片地址
                        // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
                        // 则 return res.data.url
                        response: res => {
                            return res.datas[0];
                        },
                        headers: () => {}, // 可选参数 设置请求头部
                        start: () => {}, // 可选参数 自定义开始上传触发事件
                        end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
                        error: () => {}, // 可选参数 自定义网络错误触发的事件
                        change: (xhr, formData) => {
                            formData.append('timestamp', Math.round(new Date() * 1000));
                            formData.append('port', 'pc');
                            formData.append('sign', this.getSign());
                            formData.append('key', localStorage.getItem('token'));
                        }, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
                        sizeError: () => {
                            this.$message({
                                message: '图片不能大于1M',
                                type: 'warning'
                            });
                        }
                    },
                    VideoExtend: {
                        loading: true,
                        name: 'file[]',
                        size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
                        action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
                        headers: xhr => {
                            // set custom token(optional)
                        },
                        response: res => {
                            // video uploaded path
                            // custom your own
                            return res.datas;
                        },
                        change: (xhr, formData) => {
                            formData.append('timestamp', Math.round(new Date() * 1000));
                            formData.append('port', 'pc');
                            formData.append('sign', this.getSign());
                            formData.append('key', localStorage.getItem('token'));
                        }, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
                        sizeError: () => {
                            this.$message({
                                message: '视频不能大于100M',
                                type: 'warning'
                            });
                        }
                    },
                    toolbar: {
                        container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
                        handlers: {
                            image: function() {
                                // 劫持原来的图片点击按钮事件
                                QuillWatch.emit(this.quill.id);
                            },
                            video: function() {
                                QuillVideoWatch.emit(this.quill.id);
                            }
                        }
                    }
                }
            },
            infoFormRules:{
                name: [{ required: true, message: '请填写名称' }],
                level: [{ required: true, message: '请选择等级' }],
                type: [{ required: true, message: '请填写类型' }]
            },
            levelList:[
                {
                    value:1,
                    label:"一"
                },
                {
                    value:2,
                    label:"二"
                },
                {
                    value:3,
                    label:"三"
                }
            ],
            typeList:[
                {
                    value:1,
                    label:"C端"
                },
                {
                    value:2,
                    label:"B端"
                }
            ],
            is_disabled:false,
            type:"add",
            limit:500
		};
	},
	methods: {
		// 初始化列表
		init(e) {
			this.page = e;
			let data = {
				page: e - 1 ? e - 1 : 0,
				limit: this.limit,
                order_by:this.order_by,
                asc:this.asc,
			};
			this.$http(this.$ApiList.UserManualLists, data).then(res => {
                const {datas,counts} = res
				this.total = counts;
                let list = [];
                datas.forEach(item=>{
                    let children = [];
                    if(!item.parent_id){
                        datas.forEach(data=>{
                            if(data.parent_id == item.manual_id){
                                children.push(data);
                                item.children = children
                            }
                        })
                        list.push(item);
                    }
                    
                })
                list.forEach(a=>{
                    if(a.children){
                        a.children.forEach(b=>{
                            let children = [];
                            datas.forEach(c=>{
                                if(b.manual_id == c.parent_id){
                                    children.push(c);
                                    b.children = children;
                                }
                            })
                        })
                    }
                })
                this.list = list;
			});
		},
		refreshPage() {
			this.page = 1;
			this.status = 1;
			this.selectContent = '';
            this.classSelect = 0;
			this.init();
		},
        onDel(manual_id){
            this.$confirm('删除后不可恢复, 是否确认删除?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http(this.$ApiList.OutUserManual,{manual_id}).then(res => {
					this.$message.success(res.datas);
                    this.init(this.page);
				})
			}).catch(() => {});
        },
        onOpenDialog(type,row){
            this.is_Dialog = true;
            this.type = type;
            if(type === 'add'){
                this.infoForm.parent_id = 0
                this.infoForm.level = 1;
                this.is_disabled = true;
            }else if(type === 'edit'){
                let data = JSON.parse(JSON.stringify(row));
                delete data.children;
                delete data.add_time;
                this.infoForm = data;
            }else if(type === 'next'){
                this.infoForm.level = row.level+1;
                this.is_disabled = true;
                this.infoForm.parent_id = row.manual_id;
            }
        },
        upload(type,params) {
			const file = params.file,
				isJPGPNG = file.type === 'image/jpeg' || 'image/png',
				isLt1MB = file.size / 1024 <= 10240;
			if (!isJPGPNG) {
				this.$message.error('只能上传图片格式png、jpg!');
				return;
			}
			if (!isLt1MB) {
				this.$message.error('图片不能大于10M');
				return;
			}

			let image = new FormData();
			image.append('file[]', file);

			this.$http(this.$ApiList.publicUpload, image).then(res => {
                if(type === 'no_click'){
                    this.infoForm.logo = res.datas[0];
                }else if(type === 'click'){
                    this.infoForm.logo_click = res.datas[0];
                }
			});
		},
        onClose(){
            this.is_Dialog = false;
            this.infoForm = {
                name:"",
                parent_id:"",
                level:"",
                type:"",
                content:"",
                logo:""
            }
        },
        //提交
		confirmClick(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
                    if(this.type === 'edit'){
                        this.$http(this.$ApiList.UpUserManual,this.infoForm).then(res=>{
                            this.$message.success(res.datas);
                             this.$refs[formName].resetFields();
                             this.is_Dialog = false;
                            this.init(this.page);
                        })
                    }else{
                        this.$http(this.$ApiList.AddUserManual,this.infoForm).then(res=>{
                            this.$message.success(res.datas);
                            this.is_Dialog = false;
                            this.$refs[formName].resetFields();
                            this.init(this.page);
                        })
                    }
				} else {
					this.$layer.msg('请填写完整信息后提交');
				}
			});
		},
        getSign() {
            let data = {
                key: localStorage.getItem('token'),
                timestamp: Math.round(new Date() * 1000),
                port: 'pc'
            }
            // 获取签名开始
            let obj = 'jjds2020+'
            let newObj = this.objKeySort(data)
            for (let i in newObj) {
                obj += i + '=' + newObj[i] + '&'
            }
            obj = obj.substring(0, obj.length - 1)
            obj += '+jjds2020'
            obj = md5(obj)
            return obj
        },
        // 参数排序
        objKeySort(obj) {
            var newkey = Object.keys(obj).sort();
            var newObj = {};
            for (var i = 0; i < newkey.length; i++) {
                newObj[newkey[i]] = obj[newkey[i]];
            }
            return newObj;
        },
        reset(type){
            if(type === 'no_click'){
                this.infoForm.logo = '';
            }else if(type === 'click'){
                this.infoForm.logo_click = ''
            }
            
        },
        setSelectValue(obj){
				const{ type,value } = obj
				switch (type) {
					case 'asc':
						this.asc = value
						break;
				
					default:
						break;
				}
				this.init()
			}
	},
	created() {
		this.init();
	}
};
</script>
<style lang="scss" scoped>
.video-list {
    .ql-editor{
        padding: 0px;
        height:300px;
    }
    ::v-deep .ql-container{
        height: 190px;
        .ql-editor {
			
            
			img {
				width: 100%;
			}
		}
    } 
}
</style>
